package com.talent.jiwen_teacher.my;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.afollestad.materialdialogs.MaterialDialog;
import com.talent.jiwen_teacher.R;
import com.talent.jiwen_teacher.base.BaseActivity;
import com.talent.jiwen_teacher.ui.widgets.SharePopwindow;
import com.talent.jiwen_teacher.util.SPConstant;
import com.talent.jiwen_teacher.util.SPUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by qyqx on 2018/7/20.
 */

public class WebShowActivity extends BaseActivity {

    @BindView(R.id.select_web)
    WebView h5WebView;

    @BindView(R.id.ll_bottom)
    LinearLayout ll_bottom;


    @BindView(R.id.progressBar1)
    ProgressBar progressBar1;

    public static  int WEB_SHOW_TYPE=0;

    public static final int WEB_INVISIT_TYPE=1;//邀请

    public static final int WEB_CAO_TYPE=2;//操作手册

    public static final int WEB_XIE_TYPE=3;//用户协议

    public static final int WEB_CERT_TYPE=4;//规则

    public static final int WEB_BOOK_INTRODUCE=5;//智能本操作手册

    public static final int WEB_INVISIT_MONEY=6;//邀请赚钱


    public static int IS_SERVICE_RIGHT=0;//0表示代勾 1 表示不代勾


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_web_show;
    }

    @Override
    public String titleName() {
        String title=null;
        switch (WEB_SHOW_TYPE){
            case WEB_INVISIT_TYPE:
                title="邀请有礼";
                break;
            case WEB_CAO_TYPE:
                title="操作手册";
                break;
            case WEB_XIE_TYPE:
                title="服务协议";
                break;
            case WEB_CERT_TYPE:
                title="规则中心";
                break;
            case WEB_BOOK_INTRODUCE:
                title="使用说明";
                break;
            case WEB_INVISIT_MONEY:
                title="如何邀请赚钱";
                break;
        }

        return title;
    }

    @OnClick({R.id.txt_teacher,R.id.txt_student,R.id.text_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_teacher:
                showSharePop(teacherInvisitUrl,1);
                break;
            case R.id.txt_student:
                showSharePop(studentInvisitUrl,2);
                break;
            case R.id.text_right:
                new MaterialDialog.Builder(this)
                        .title("即问邀请规则")
                        .content(
                                "一、邀请的人员分为两类，一是教师，二是学生。\n\n" +
                                "二、推荐奖励：\n"+
                                "1.首次交易奖励 15元（注册成功，并且被邀请者产生首次支付的订单，订单上课时间在15分钟以上，直接奖励15元但没有提成。奖励将累计在余额中，可提现，首单奖励无提拥）。\n" +
                                "2.一线单 1.2元/单，二线单0.5元/单 （每单交易时长必须在15分钟以上）。\n" +
                                "3.一线单 0.5元/单，二线单0.3元/单 （每单交易时长为5-15分钟，含15分钟，低于5分钟将不能获得提成。\n" +
                                "备注：\n"+
                                "（1）一线单：邀请码被直接关联，此被邀请者产生的订单称为一线单;\n"+
                                "（2）二线单：一线单的被邀请者邀请的被邀请者所产生的订单称之为下线单;\n"+
                                "（3）所有被邀请者均不能重复，如有重复只算其中一个被邀请关系。\n\n"+
                                "三、股权奖励：\n"+
                                "您一旦获得股权奖励意味着您将成为本公司的股东，将会获得相关的股权证书和享有相关股东权益，股权奖励条件：\n"+
                                "1.推荐学生总人数排在公司前5%的介绍人将获得公司股权 （推荐学生数不低于50人，被推荐人每月在“即问”平台上课次数不低于4次，每次不低20分钟，低于此标准者不列入评估范围）。\n"+
                                "2.推荐老师总人数排在公司前5%的介绍人将获得公司股权（推荐老师数不低于15人，被介绍人每月在“即问”平台授课日均时长不低于30分钟，低于标准者不列入评估范围）。\n"+
                                "3.第一年的奖励基数为2000股；第二年的奖励基数为1000股；第三年的奖励基数为1000股。\n\n"+
                                "四、邀请违规判定标准：\n" +
                                "1.只有注册，没有交易，判定为无效邀请。\n" +
                                "2.老师资格造假，判定为无效邀请，邀请人做警告，严重者封号。\n" +
                                "3.课堂进行时自说自话，文不对题，判定为无效交易，并列为刷单行为。\n" +
                                "4.学生有投诉情况发生并成立，判定无效交易。\n"+
                                "5.无效交易将不能参与以上的奖励条款。"
                        )
                        .positiveText("确定")
                        .showListener(new DialogInterface.OnShowListener() {
                            @Override
                            public void onShow(DialogInterface dialog) {
                            }
                        })
                        .cancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                            }
                        })
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                            }
                        }).show();
                break;
        }}


    private void showSharePop(String url,int type){
        SharePopwindow pop=new SharePopwindow(WebShowActivity.this,0,url,SPUtil.getUserName(),type);
        pop.showAtLocation(WebShowActivity.this.findViewById(R.id.view),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    String EDU_URL = "http://www.uixkid.com";
//    String EDU_URL = "http://192.168.0.160:8080";
      //无注册功能
//    String studentInvisitUrl=EDU_URL+"/customerIndex/studentPartTime?code="+ SPUtil.stringOut(SPConstant.INVITE_CODE)+"&name="+SPUtil.getUserName();
//    String teacherInvisitUrl=EDU_URL+"/customerIndex/teacherPartTime?code="+ SPUtil.stringOut(SPConstant.INVITE_CODE)+"&name="+SPUtil.getUserName();

    String studentInvisitUrl=EDU_URL+"/customerIndex/studentInviteAndReg?code="+ SPUtil.stringOut(SPConstant.INVITE_CODE)+"&name="+SPUtil.getUserName();
    String teacherInvisitUrl=EDU_URL+"/customerIndex/teacherInviteAndReg?code="+ SPUtil.stringOut(SPConstant.INVITE_CODE)+"&name="+SPUtil.getUserName();

    private void getWord(String str){
        try {
            String result = URLEncoder.encode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initData() {
        switch (WEB_SHOW_TYPE){
            case WEB_INVISIT_TYPE:
                ll_bottom.setVisibility(View.VISIBLE);
                mHeadRightText.setVisibility(View.VISIBLE);
                mHeadRightText.setText("规则");
                mHeadRightText.setTextColor(getResources().getColor(R.color.text_gray_9));
                webUrl=EDU_URL+"/customerIndex/invitation?id="+SPUtil.getUserId()+"&type=1";
                break;
            case WEB_CAO_TYPE:
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
                webUrl=EDU_URL+"/customerIndex/appOperation";
                break;
            case WEB_XIE_TYPE:
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
                if(IS_SERVICE_RIGHT==0){
                    webUrl=EDU_URL+"/customerIndex/teacherAgreement?type=0";
                }else{
                    webUrl=EDU_URL+"/customerIndex/teacherAgreement?type=1";
                }
                break;
            case WEB_CERT_TYPE://规则中心
                webUrl=EDU_URL+"/customerIndex/commissionRules";
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
//                webUrl=EDU_URL+"/customerIndex/teacherPartTime";
                break;
            case WEB_BOOK_INTRODUCE:
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
                webUrl=EDU_URL+"/customerIndex/handpadManual";
                break;
            case WEB_INVISIT_MONEY:
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
                webUrl=EDU_URL+"/customerIndex/jumpToInvitationProcess";
                break;
        }
        initWeb();
    }

        /**
         * LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
         * LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
         * LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
         * LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
         */
//        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存，只从网络获取数据.
//
//        //支持屏幕缩放
//        webSettings.setSupportZoom(true);
//        webSettings.setBuiltInZoomControls(true);

        //不显示webview缩放按钮
//        webSettings.setDisplayZoomControls(false);
//
//    }
    private String webUrl ;

    // 初始化webview
    @SuppressLint("SetJavaScriptEnabled")
    private void initWeb() {

        WebSettings mWebSettings = h5WebView.getSettings();
        mWebSettings.setJavaScriptEnabled(true); //允许加载javaScript
        mWebSettings.setSupportZoom(true);       //是否允许缩放
        mWebSettings.setUseWideViewPort(true);   //设置加载进来的页面自适应手机屏幕
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        h5WebView.setWebViewClient(new WebViewClient(){
            //覆写shouldOverrideUrlLoading实现内部显示网页
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO 自动生成的方法存根
                if (url != null && url.contains("/html/html")) {
                    Intent intent = new Intent();
                    setResult(1001, intent);
                    finish();
                }else{
                    view.loadUrl(url);
                }

                return true;
            }
        });


        h5WebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根

                if(newProgress==100){
                    progressBar1.setVisibility(View.GONE);//加载完网页进度条消失
                }
                else{
                    progressBar1.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBar1.setProgress(newProgress);//设置进度值
                }
            }
        });

        h5WebView.canGoBack();
        h5WebView.loadUrl(webUrl);

        //H5界面加载进度监听
//        h5WebView.setWebChromeClient(new WebChromeClient(){
//            @Override
//            public void onProgressChanged(WebView view, int newProgress) {
//
////                if (webProgressBar != null){
////                    if (newProgress > 95){
////                        webProgressBar.setVisibility(View.GONE);
////                    }else if (newProgress < 95 && webProgressBar.getVisibility() == View.GONE){
////                        webProgressBar.setVisibility(View.VISIBLE);
////                    }
////                    webProgressBar.setProgress(newProgress);
////                }
//                super.onProgressChanged(view, newProgress);
//            }
//        });

        /**
         * 监听手机返回按键，点击返回H5就返回上一级
         */
        h5WebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK) && h5WebView.canGoBack()) {
                    h5WebView.goBack();
                    return true;
                }
                return false;
            }
        });
    }

        @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放资源
            h5WebView.destroy();
            h5WebView=null;
    }

}
